import numpy as np
import matplotlib.pyplot as plt
import time
import wave
import struct
import os

# Parameters for audio output
SAMPLE_RATE = 44100
VOLUMN = 2**14
SQ = False  # if True, output square wave, otherwise sine wave

# frequency of the high tone (Base Tone, in my eyes)
C = 440*(2**4)  # Do, middle C at 440Hz
D = int(C * np.power(2, 2/12.0))  # Re
E = int(C * np.power(2, 4/12.0))  # Mi
F = int(C * np.power(2, 5/12.0))  # Fa
G = int(C * np.power(2, 7/12.0))  # So
A = int(C * np.power(2, 9/12.0))  # La
B = int(C * np.power(2, 11/12.0)) # Si

TONE_PATH = str(C)


print('path: ', TONE_PATH)
# 1 second long tone wave --> sin(2 * pi * f * linespace(0s, 1s, SAMPLE_RATE))
t = 1
if SQ:
    TONE_PATH = 'sq%s' % TONE_PATH
    a = 0
    waves = {
        '1': VOLUMN * (np.sin(2*np.pi*C * np.linspace(0, t, t * SAMPLE_RATE)) > a),
        '2': VOLUMN * (np.sin(2*np.pi*D * np.linspace(0, t, t * SAMPLE_RATE)) > a),
        '3': VOLUMN * (np.sin(2*np.pi*E * np.linspace(0, t, t * SAMPLE_RATE)) > a),
        '4': VOLUMN * (np.sin(2*np.pi*F * np.linspace(0, t, t * SAMPLE_RATE)) > a),
        '5': VOLUMN * (np.sin(2*np.pi*G * np.linspace(0, t, t * SAMPLE_RATE)) > a),
        '6': VOLUMN * (np.sin(2*np.pi*A * np.linspace(0, t, t * SAMPLE_RATE)) > a),
        '7': VOLUMN * (np.sin(2*np.pi*B * np.linspace(0, t, t * SAMPLE_RATE)) > a),
    }
else:
    waves = {
        '1': VOLUMN * np.sin(2*np.pi*C * np.linspace(0, t, t * SAMPLE_RATE)),
        '2': VOLUMN * np.sin(2*np.pi*D * np.linspace(0, t, t * SAMPLE_RATE)),
        '3': VOLUMN * np.sin(2*np.pi*E * np.linspace(0, t, t * SAMPLE_RATE)),
        '4': VOLUMN * np.sin(2*np.pi*F * np.linspace(0, t, t * SAMPLE_RATE)),
        '5': VOLUMN * np.sin(2*np.pi*G * np.linspace(0, t, t * SAMPLE_RATE)),
        '6': VOLUMN * np.sin(2*np.pi*A * np.linspace(0, t, t * SAMPLE_RATE)),
        '7': VOLUMN * np.sin(2*np.pi*B * np.linspace(0, t, t * SAMPLE_RATE)),
    }


for k in waves:
    if not os.path.isdir(TONE_PATH):
        os.mkdir(TONE_PATH)
        
    w = wave.open(os.path.join(TONE_PATH, '%s.wav'%k), 'wb')
    w.setnchannels(1)
    w.setsampwidth(2)
    w.setframerate(SAMPLE_RATE)
    sound = waves[k]
    for i in sound:
        w.writeframesraw(struct.pack("<hh", int(i), int(i)))
    w.writeframes(b"")
    w.close()


"""
y = waves['1'][:300]
# y = y > 500
plt.plot(y)
plt.show()
"""
print('All done')
